<?php
#
# dmBridge: a data access framework for CONTENTdm(R)
#
# Copyright © 2009, 2010, 2011 Board of Regents of the Nevada System of Higher
# Education, on behalf of the University of Nevada, Las Vegas
#

/**
 * Static class providing access to localized strings. Built-in localized
 * strings are named "strings.code.txt" where "code" is an ISO 639-1 language
 * code. Strings are returned according to the "dmbridge.language" setting in
 * config.ini. If a strings file matching the "dmbridge.language" setting
 * cannot be found, the English strings file will be used.
 * 
 * @author Alex Dolski <alex.dolski@unlv.edu>
 * @license http://www.opensource.org/licenses/mit-license.php
 */
abstract class DMLocalizedString {

	/** @var array Array of string arrays, lazy-loaded by getString() and
	 * keyed by md5 of the strings file path */
	private static $strings = array();
	
	/**
	 * @param string key Key of the string to retrieve
	 * @param string strings_folder Absolute pathname of an alternate folder
	 * in which to look for strings files
	 * @return string
	 */
	public static function getString($key, $strings_folder = null) {
		$strings_folder = $strings_folder
			? $strings_folder : dirname(__FILE__) . "/../../includes/strings";
		$code = DMConfigIni::getInstance()->getString("dmbridge.language", "en");
		$pathname = $strings_folder . "/strings." . $code . ".txt";
		if (!file_exists($pathname)) {
			$pathname = $strings_folder . "/strings.en.txt";
		}
		$sum = md5($pathname);
		if (!array_key_exists($sum, self::$strings)) {
			self::$strings[$sum] = array();
			$fh = fopen($pathname, "rb");
			while (!feof($fh)) {
				$line = fgets($fh);
				$parts = explode('=', $line);
				$str_key = array_shift($parts);
				self::$strings[$sum][trim($str_key)]
						= trim(implode("=", $parts));
			}
			fclose($fh);
		}

		$key = strtoupper($key);
		foreach (self::$strings as $path_sum => $strings) {
			if ($path_sum == $sum) {
				return (array_key_exists($key, $strings))
						? $strings[$key] : null;
			}
		}
	}

}
